//index.js
//获取应用实例
var util = require('../../utils/util.js');
const qiniuUploader = require("../../utils/qiniuUploader");
const app = getApp()

Page({
  data: {
    types: ["请选择","公共课教材", "专业教材", "专业书籍", "课外书籍"],
    typeIndex: 0,
    brief_intro: "糟了，这本书没有简介",
    imageUrls: [
    ],
    num: 1
  },
  bindTypeChange: function (e) {

    this.setData({
      typeIndex: e.detail.value
    })
  },

  chooseImage: function(e){
    var that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        var tempFilePath = res.tempFilePaths[0];
        wx.showLoading({
          title: '正在上传中',
          mask: true
        })
        qiniuUploader.upload(tempFilePath, (res) => {
          let urls = that.data.imageUrls;
          urls.push("https://" + res.imageURL)
          that.setData({
            'imageUrls': urls,
          });
          wx.hideLoading()
        }, (error) => {
          console.log('error: ' + error);
        }, {
            region: 'ECN',
            uploadURL: 'https://qiniu.bookin.moha.vip',
            domain: 'qiniu.bookin.moha.vip', 
            uptokenURL: "https://bookin.moha.vip/uptoken/",
            shouldUseQiniuFileName: true
          }, (res) => {
            console.log(res)
          });
      }
    })
  },

  bindDepartmentChange: function (e) {

    this.setData({
      departmentIndex: e.detail.value
    })
  },
  formSubmit: function (e) {
    // form 表单取值，格式 e.detail.value.name(name为input中自定义name值) ；使用条件：需通过<form bindsubmit="formSubmit">与<button formType="submit">一起使用  
    var category = this.data.typeIndex;
    var className = e.detail.value.class;
    var bookName = e.detail.value.bookName;
    var price = e.detail.value.price;
    var num = e.detail.value.num;
    var address = e.detail.value.address;
    var note = e.detail.value.note;
    var brief_intro = this.data.brief_intro;
    var origin_price = this.data.origin_price;
    var that = this;

    if (category == 0){
      wx.showToast({
        icon: "none",
        title: '类型不能为空',
      })
      return;
    }

    if ("" == util.trim(className)) {
      wx.showToast({
        icon: "none",
        title: '课程名字不能为空',
      })
      return;
    } else {
      util.clearError(that);
    }
 
    if ("" == util.trim(bookName)) {
      wx.showToast({
        icon: "none",
        title: '书名不能为空',
      })
      return;
    } else {
      util.clearError(that);
    }

    if ("" == util.trim(price)) {
      wx.showToast({
        icon: "none",
        title: '价格不能为空',
      })
      return;
    } else {
      util.clearError(that);
    }

    if ("" == util.trim(num)) {
      wx.showToast({
        icon: "none",
        title: '数量不能为空',
      })
      return;
    } else {
      util.clearError(that);
    }

    if ("" == util.trim(address)) {
      wx.showToast({
        icon: "none",
        title: '地址不能为空',
      })
      return;
    } else {
      util.clearError(that);
    }
    wx.showLoading({
      title: '正在提交',
    })
    wx.getStorage({
      key: 'cookie',
      success: function (res) {
        var cookie = res.data;
        var header = util.getCommonHeaders(cookie);
        wx.request({
          url: util.getRoot() + '/book/book_list/',
          data: {
            "category": parseInt(category),
            "course": className,
            "book_name": bookName,
            "price": parseFloat(price) + 0.0,
            "number": parseInt(num),
            "trade_place": address,
            "notes": note,
            "book_pic": that.data.imageUrls.join(" "),
            "brief_intro": brief_intro,
            "origin_price": origin_price
          },
          method: 'put',
          header: header,
          success: res => {
            if(res.statusCode != 201){
              wx.showToast({
                icon: "none",
                title: '出错啦',
              })
              return;
            }
            var book_id = res.data["book_id"];
            wx.redirectTo({
              url: '/pages/bookDetail/bookDetail?id=' + book_id,
            })
          },
          fail: () => {
            wx.showToast({
              icon: "none",
              title: '操作失败请重试',
            })
            return;
          },
          complete: function(){
            wx.hideLoading();
          }
        })
      },
      fail: function(){
        wx.showToast({
          icon: "none",
          title: '操作失败请重试',
        })
        wx.hideLoading();
      }
    })
  },

  toAutoFill: function(e){
    var that = this;
    wx.scanCode({
      scanType: 'barCode',
      success: function(res){
        var isbn = res.result;
        wx.showLoading({
          title: '正在加载中...',
        })
        wx.request({
          url: 'https://bookin.moha.vip/book/douban/?isbn=' + isbn,
          success: res=>{
            if(res.statusCode !== 200){
              wx.showModal({
                title: '扫描错误',
                content: '请扫描合法的条形码',
                showCancel: false
              })
            }else{
              var data = res.data;
              var imageUrls = that.data.imageUrls;
              imageUrls.push("https://qiniu.bookin.moha.vip/" + data["pic"])
              that.setData({
                imageUrls: imageUrls,
                bookName: data["book_name"],
                brief_intro: data["summary"],
                origin_price: data["price"]
              });
              wx.showToast({
                title: '填充完成！',
              })
            }
          },
          complete: res=>{
            wx.hideLoading();
          }
        })
      }
    })
  },

  toDelete: function(e){
    let that = this;
    let id = e.target.dataset.index;
    let urls = this.data.imageUrls;
    wx.showModal({
      title: '删除',
      content: '确定要删除这个图片吗？',
      success: (res)=>{
        if(res.cancel) return;
        let newUrl = [];
        for(let i in urls){
          if(i == id) continue;
          newUrl.push(urls[i]);
        }
        that.setData({
          imageUrls: newUrl
        })
      }
    })
  }
})